from django.shortcuts import render
from driver_school_after.utils import is_blank,get_token
from django.core.paginator import Paginator
from rest_framework.decorators import api_view
from login.models import Student_text
from login.models import Student
from login.models import Subject
from django.http import JsonResponse

from rest_framework.parsers import JSONParser
from student_text.utils import set_token,get_token
# Create your views here.


# 查询预约的考试


@api_view(['get'])
def student_text_select(request):

    token=request.headers.get('token')
    jiema=get_token(token)


    page = int(request.GET.get('page'))
    pagesize = int(request.GET.get('pagesize'))

    # 使用select_related优化查询，获取关联对象
    kaoshi = Student_text.objects.filter(student__name=jiema['name']).select_related('student', 'subject')

    # 排序以避免分页警告
    kaoshi = kaoshi.order_by('test_id')

    # 分页
    paginator = Paginator(kaoshi, pagesize)
    paginatorobj = paginator.get_page(page)

    info = []
    for item in paginatorobj.object_list:
        info.append({
            "test_id": item.test_id,
            "student_name": item.student.name,  # 直接通过关联对象访问
            "student_phone": item.student.phone,
            "ground": item.ground,
            "session": item.session
        })

    return JsonResponse({
        "status": 200,
        "message": "查询成功",
        "data": info,
        "total": paginator.count
    })


# 添加预约考试
@api_view(['post'])
def add_test(request):
    # 判断是否登录
    token = request.headers.get('token')
    if is_blank(token):
        return JsonResponse({"status": 203, "message": "请先登录"})

    gettoken = get_token(token)
    print(gettoken)

    data = JSONParser().parse(request)


    Student_text(**data).save()
    return JsonResponse({"status": 200, "message": "添加成功"})
